/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean;

import java.io.*;
import com.lowagie.text.DocumentException;
import java.net.URL;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.RequestScoped;
import javax.faces.bean.ManagedBean;
import javax.servlet.http.HttpServletRequest;
import org.xhtmlrenderer.pdf.ITextRenderer;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author thanhle
 */
@ManagedBean(name = "pdfDownload")
@SessionScoped
public class PdfDownload {



    public static  String getPdfPath(String name) {
        String home_path = System.getProperty("user.home");
        String path;
        if (home_path.indexOf("\\") > 0) {

            path = home_path + "\\" + name + ".pdf";
            System.out.println(path + "hhh");
        } else {
            path = home_path + "/" + name + ".pdf";
        }
        return path;
    }

    public static void generatePDFFromUrlThanh(String name, String page) {
        OutputStream os = null;

        String outputFile = getPdfPath(name);
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExternalContext externalContext = facesContext.getExternalContext();
        String servername = externalContext.getRequestServerName();
        String port = String.valueOf(externalContext.getRequestServerPort());
        String appname = externalContext.getRequestContextPath();
        String protocol = externalContext.getRequestScheme();
        String url = protocol + "://" + servername + ":" + port + appname + "/pdf/" + page;

  
        try {

            os = new FileOutputStream(outputFile);

            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocument(url);
            renderer.layout();
            renderer.createPDF(os);
            os.close();

        } catch (Exception ex) {
            Logger.getLogger(PdfDownload.class.getName()).log(Level.SEVERE, null, ex);
        }
        facesContext.responseComplete();
    }
}
